package cn.tsingmo.otproxy.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TcpProxyClient {
    private static final Logger logger = LoggerFactory.getLogger(TcpProxyClient.class);
    private final String proxyHost;
    private final int proxyPort;
    private final String targetHost;
    private final int targetPort;

    public TcpProxyClient(String proxyHost, int proxyPort, String targetHost, int targetPort) {
        this.proxyHost = proxyHost;
        this.proxyPort = proxyPort;
        this.targetHost = targetHost;
        this.targetPort = targetPort;
    }

    public void start() throws Exception {
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ClientInitializer(targetHost, targetPort));
                }
            });

            // 连接到服务器
            ChannelFuture f = b.connect(proxyHost, proxyPort).sync();
            logger.info("Connected to OTProxy server at {}:{}", proxyHost, proxyPort);

            // 等待连接关闭
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            logger.info("OTProxy client disconnected");
        }
    }
}